#include <am.h>
#include <nemu.h>
#include <klib.h>

extern char _bss_end;

extern char _heap_start;
extern char _heap_end;
int main(const char *args);

// Area heap = RANGE(&_heap_start, PMEM_END);
Area heap = RANGE(&_heap_start, &_heap_end);
#ifndef MAINARGS
#define MAINARGS ""
#endif
static const char mainargs[] = MAINARGS;

void putch(char ch) {
  outb(SERIAL_PORT, ch);
}

void halt(int code) {
  nemu_trap(code);

  // should not reach here
  while (1);
}

void info_cpu() {
  unsigned int mvendorid = 0;
  unsigned int marchid = 0;

  asm volatile("csrr %0, mvendorid" : "=r"(mvendorid));
  asm volatile("csrr %0, marchid" : "=r"(marchid));
  putch(mvendorid >> 24);
  putch((mvendorid & 0x00ff0000) >> 16);
  putch((mvendorid & 0x0000ff00) >> 8);
  putch(mvendorid & 0x000000ff);
  printf("%d\n", marchid);
}

void _trm_init() {
  info_cpu();
  int ret = main(mainargs);
  halt(ret);
}
